// 引入登录|退出登录|获取用户信息的接口函数
import { login, logout, getInfo } from '@/utils/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 存储用户令牌和角色信息
const state ={
    token: getToken(),
    roles: [] //角色
}

const mutations ={
    SET_TOKEN: (state,token) => {
        state.token = token;
    },
	SET_ROLES: (state,roles) => {
	        state.roles = roles;
	},
    // 存储用户信息
    SET_USERINFO: (state, userInfo) => {
      // 用户名
      state.name = userInfo.username
      state.userId = userInfo.userId
      // 用户头像
      // state.avatar = userInfo.avatar
      // 菜单权限标记
      // state.routes = userInfo.routes
      // 按钮权限标记
      // state.buttons = userInfo.buttons
      // 角色
      // state.roles = userInfo.roles
    },
};

const actions = {
    // 用户登录
    // 这里在处理登录业务
    async login({ commit }, userInfo) {
		console.log(userInfo)
		state.name = userInfo.username
      // 解构出用户名与密码
      const { username, password,captcha,uuid} = userInfo
      const result = await login({ username: username.trim(), password: password ,captcha:captcha,uuid:uuid})
      // 注意：当前登录请求现在使用mock数据，mock数据code是20000
      if (result.code == 200) {
        // vuex存储token
        commit('SET_TOKEN', result.token)
        // 本地持久化存储token
        setToken(result.token);
		let oneid=sessionStorage.getItem('oneid');
		sessionStorage.setItem('menuId',oneid);
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 获取用户角色信息
    // getInfo({ commit, state }){
    //     return new Promise((resolve) => {
    //         setTimeout(() => {
    //             const roles = state.token === 'admin' ? ['admin'] : ['jerry']
    //             commit('SET_ROLES',roles)
    //             resolve({roles})
    //         },1000)
    //     })
    // },
	async getInfo({ commit, state }) {
		 const result = await  getInfo(state.token)
		 return new Promise((resolve) => {
			 if (result.code == 200) {
			 			const roles = state.token === 'admin' ? ['admin'] : ['jerry']
			 			commit('SET_ROLES',roles)
			 			commit('SET_USERINFO', result.user)
						resolve({roles})
			 } else {
			   Promise.reject(new Error('faile'))
			 }
		 }).catch(error => {})
	},
	// user logout
	async logout({ commit, state }) {
		 const result = await logout(state.token)
		 if (result.code == 200) {
		   // vuex存储token
		  commit('SET_TOKEN','')
		  commit('SET_USERINFO',[])
		   return 'ok'
		 } else {
		   return Promise.reject(new Error('faile'))
		 }
	  
	},
    // 重置令牌
    resetToken({ commit }){
        return new Promise(resolve => {
            commit('SET_TOKEN','')
            commit('SET_USERINFO',[])
            removeToken();
            resolve()
        }).catch(error => {})
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}